<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

// 获取 DOM 元素的引用（用于初始化图表）
const chartRef = ref(null)
// 存储 ECharts 实例
let chartInstance = ref(null)

var xAxisData = [];
var data1 = [];
var data2 = [];
for (var i = 0; i < 100; i++) {
    xAxisData.push('A' + i);
    data1.push((Math.sin(i / 5) * (i / 5 - 10) + i / 6) * 5);
    data2.push((Math.cos(i / 5) * (i / 5 - 10) + i / 6) * 5);
}

// 初始化图表的方法
const initChart = () => {
    if (chartRef.value) {
        // 初始化 echarts 实例
        chartInstance = echarts.init(chartRef.value)
        // 配置项
        const option = {
            title: {
                text: 'Bar Animation Delay'
            },
            legend: {
                data: ['bar', 'bar2']
            },
            toolbox: {
                // y: 'bottom',
                feature: {
                    magicType: {
                        type: ['stack']
                    },
                    dataView: {},
                    saveAsImage: {
                        pixelRatio: 2
                    }
                }
            },
            tooltip: {},
            xAxis: {
                data: xAxisData,
                splitLine: {
                    show: false
                }
            },
            yAxis: {},
            series: [
                {
                    name: 'bar',
                    type: 'bar',
                    data: data1,
                    emphasis: {
                        focus: 'series'
                    },
                    animationDelay: function (idx) {
                        return idx * 10;
                    }
                },
                {
                    name: 'bar2',
                    type: 'bar',
                    data: data2,
                    emphasis: {
                        focus: 'series'
                    },
                    animationDelay: function (idx) {
                        return idx * 10 + 100;
                    }
                }
            ],
            animationEasing: 'elasticOut',
            animationDelayUpdate: function (idx) {
                return idx * 5;
            }
        };
        // 使用配置项渲染图表
        chartInstance.setOption(option)
        // 主动触发一次 resize，确保地图显示
        chartInstance.resize();
    }
}

// 窗口大小变化时调整图表尺寸
const resizeChart = () => {
    chartInstance?.resize()
}

// 组件挂载后执行初始化
onMounted(() => {
    initChart()
    // 监听窗口大小变化事件以支持响应式
    window.addEventListener('resize', resizeChart)
})

// 组件卸载前清理资源，防止内存泄漏
onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeChart)
    chartInstance?.dispose() // 销毁 echarts 实例
})
</script>

<template>
    <div ref="chartRef" style="width: 100%; height: 300px;"></div>
</template>

<style scoped></style>
